<template>
    <div class="boxs">
        <el-card>
            <el-form :model="queryParams" ref="queryForm" :inline="true">
                <el-form-item :label="$t('review.language')">
                    <el-select v-model="queryParams.target_language" @change="handleQuerySingle">
                        <el-option v-for="item in languageList" :key="item.id" :label="item.name"
                            :value="item.name"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <!-- <el-button type="primary" icon="el-icon-search" size="small"
                        @click="handleQuery">{{ $t('table.search') }}</el-button> -->
                    <el-button icon="el-icon-refresh" size="small"
                        @click="resetQuery">{{ $t('table.reset') }}</el-button>
                </el-form-item>
            </el-form>
            <div class="flex_between">
                <div></div>
                <div class="flex_between">
                    <el-button type="primary" size="small"
                        @click="oneClickTranslationHandel">{{ $t('translation.translateall') }}</el-button>
                    <el-button type="warning" icon="el-icon-upload" size="small"
                        @click="submitHandel">{{ $t('translation.submit') }}</el-button>
                </div>
            </div>
            <el-table border :data="moreArr" style="margin-top: 15px" v-loading="loading">
                <el-table-column label="index" align="center" width="60" type="index" />
                <el-table-column :label="$t('translation.stringContent') " align="center" prop="stringContent" />
                <el-table-column v-if="single" :label="$t('translation.translationResult') " align="center"
                    prop="translation_result" />
                <el-table-column :label="$t('translation.translatestate') " width="130" align="center" prop="childFlag">
                    <template slot-scope="scope">
                        <el-tag type="danger"
                            v-if="scope.row.childFlag == '0'">{{ $t('translation.stateNo') }}</el-tag>
                        <el-tag type="success"
                            v-if="scope.row.childFlag == '1'">{{ $t('translation.stateYes') }}</el-tag>
                        <el-tag type="info"
                            v-if="scope.row.childFlag == '2'">{{ $t('translation.Excludetranslation') }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column :label="$t('translation.Operator') " align="center" fixed="right" width="100">
                    <template slot-scope="scope">
                        <el-button :disabled="scope.row.childFlag == '2'" size="mini"
                            @click="handleEdit(scope.$index, scope.row)">{{ $t('translation.Edit') }}</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="total > 0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.size"
                @pagination="getHandler()" />
        </el-card>

        <el-dialog :title="$t('translation.Operator')" :visible.sync="dialogVisible" width="40%">
            <el-form class="demo-form-inline" label-width="150px" :model="form" :rules="rules" ref="ruleForm">
                <el-form-item :label="$t('translation.stringContent')" prop="stringContent">
                    <el-input v-model="form.stringContent" :disabled="single" placeholder="请输入" type="textarea"
                        autosize />
                </el-form-item>
                <div v-if="form.translationResults && form.translationResults.length">
                    <el-form-item :key="item.index" v-for="item in displayedTranslationResults"
                        :label="item.targetLanguage" :prop="'translationResults[' + item.index + '].translationResult'">
                        <el-input v-model="form.translationResults[item.index].translationResult" placeholder="请输入"
                            type="textarea" autosize />
                    </el-form-item>
                </div>
                <!-- <el-form-item label="">
                    <el-button style="margin-bottom: 22px" :loading="translateLoading" @click="translateHandel"
                        type="primary">一键翻译</el-button>
                </el-form-item> -->
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">{{
                $t("review.close")
            }}</el-button>
                <el-button :loading="confirmLoading" :type="form.id ? 'warning' : 'primary'" @click="affirm">{{
                form.id ? $t("review.confirm") : $t("review.confirm")
            }}</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import { getChildTaskList, childTaskTranslateTextForMultiLang, saveChildBatch, saveSubmit, getLangListByPk, getChildTaskListSingle, oneClickTranslation } from "@/api/translate";

import pk from "@/utils/pk";
export default {
    name: "childTaskList",
    data() {
        return {
            queryParams: {
                page: 1,
                size: 10,
                packageName: "",
                target_language: '',
                version:''
            },
            total: 0,
            loading: false,
            addLoading: false,
            moreArr: [],
            languageList: [],
            dialogVisible: false,
            translateLoading: false,
            form: {
                translationResults: []
            },
            search: "",
            rules: {
                stringContent: [
                    { required: true, message: "请输入描述", trigger: "blur" },
                ],

            },
            value1: "",
            confirmLoading: false,
            single: false,
            resList1: [
                {
                    target_language: 'ar',
                    string_content: '我是字段1',
                    translation_result: '我是翻译成ar语言的字段1',
                    translationResults: ''
                },
                {
                    target_language: 'ar',
                    string_content: '我是字段2',
                    translation_result: '我是翻译成ar语言的字段2',
                    translationResults: ''
                },
                {
                    target_language: 'id',
                    string_content: '我是字段1',
                    translation_result: '我是翻译成id语言的字段1',
                    translationResults: ''
                },
                {
                    target_language: 'id',
                    string_content: '我是字段2',
                    translation_result: '我是翻译成id语言的字段2',
                    translationResults: ''
                },
                {
                    target_language: 'ko',
                    string_content: '我是字段1',
                    translation_result: '我是翻译成ko语言的字段1',
                    translationResults: ''
                },
                {
                    target_language: 'ko',
                    string_content: '我是字段2',
                    translation_result: '我是翻译成ko语言的字段2',
                    translationResults: ''
                },
            ],

            resList2: [
                {
                    target_language: 'ar',
                    string_content: '我是字段1',
                    translation_result: '我是翻译成ar语言的字段1',
                    translationResults: [
                        {
                            targetLanguage: "ar",
                            translationResult: "我是翻译成ar语言的字段1"
                        },
                        {
                            targetLanguage: "id",
                            translationResult: "我是翻译成id语言的字段1"
                        },
                        {
                            targetLanguage: "ko",
                            translationResult: "我是翻译成ko语言的字段1"
                        }
                    ]
                },
                {
                    target_language: 'ar',
                    string_content: '我是字段2',
                    translation_result: '我是翻译成ar语言的字段2',
                    translationResults: [
                        {
                            targetLanguage: "ar",
                            translationResult: "我是翻译成ar语言的字段2"
                        },
                        {
                            targetLanguage: "id",
                            translationResult: "我是翻译成id语言的字段2"
                        },
                        {
                            targetLanguage: "ko",
                            translationResult: "我是翻译成ko语言的字段2"
                        }
                    ]
                },
                {
                    target_language: 'id',
                    string_content: '我是字段1',
                    translation_result: '我是翻译成id语言的字段1',
                    translationResults: [
                        {
                            targetLanguage: "ar",
                            translationResult: "我是翻译成ar语言的字段1"
                        },
                        {
                            targetLanguage: "id",
                            translationResult: "我是翻译成id语言的字段1"
                        },
                        {
                            targetLanguage: "ko",
                            translationResult: "我是翻译成ko语言的字段1"
                        }
                    ]
                },
                {
                    target_language: 'id',
                    string_content: '我是字段2',
                    translation_result: '我是翻译成id语言的字段2',
                    translationResults: [
                        {
                            targetLanguage: "ar",
                            translationResult: "我是翻译成ar语言的字段2"
                        },
                        {
                            targetLanguage: "id",
                            translationResult: "我是翻译成id语言的字段2"
                        },
                        {
                            targetLanguage: "ko",
                            translationResult: "我是翻译成ko语言的字段2"
                        }
                    ]
                },
                {
                    target_language: 'ko',
                    string_content: '我是字段1',
                    translation_result: '我是翻译成ko语言的字段1',
                    translationResults: [
                        {
                            targetLanguage: "ar",
                            translationResult: "我是翻译成ar语言的字段1"
                        },
                        {
                            targetLanguage: "id",
                            translationResult: "我是翻译成id语言的字段1"
                        },
                        {
                            targetLanguage: "ko",
                            translationResult: "我是翻译成ko语言的字段1"
                        }
                    ]
                },
                {
                    target_language: 'ko',
                    string_content: '我是字段2',
                    translation_result: '我是翻译成ko语言的字段2',
                    translationResults: [
                        {
                            targetLanguage: "ar",
                            translationResult: "我是翻译成ar语言的字段2"
                        },
                        {
                            targetLanguage: "id",
                            translationResult: "我是翻译成id语言的字段2"
                        },
                        {
                            targetLanguage: "ko",
                            translationResult: "我是翻译成ko语言的字段2"
                        }
                    ]
                },
            ],
        };
    },
    created() {
        //获取当前路由
        this.queryParams.packageName = this.extractedString;
        this.queryParams.version = this.$route.query.version;
        this.getMore();
        this.addValidationRules();
        this.getLangListByPkHandel();
        // console.log(this.enrichTranslationResults(this.resList1))

    },
    watch: {
        'form.translationResults': {
            handler(newVal) {
                this.addValidationRules();
            },
            deep: true
        }
    },
    computed: {
        currentPath() {
            return this.$route.path;
        },
        extractedString() {
            return this.getSubstringAfter(this.currentPath, "childTaskList-");
        },
        displayedTranslationResults() {
            if (this.single) {
                return this.form.translationResults
                    .map((item, index) => ({ ...item, index })) // 保留每个 `item` 的索引
                    .filter(item => item.targetLanguage === this.queryParams.target_language);
            } else {
                return this.form.translationResults
                    .map((item, index) => ({ ...item, index })); // 直接返回包含索引的所有项
            }
        }
    },
    methods: {
        enrichTranslationResults(resList) {
            const translationsByLanguage = resList.reduce((acc, item) => {
                acc[item.target_language] = acc[item.target_language] || [];
                acc[item.target_language].push({
                    string_content: item.string_content,
                    translation_result: item.translation_result
                });
                return acc;
            }, {});

            return resList.map(item => {
                const currentLanguageTranslations = translationsByLanguage[item.target_language];

                const otherLanguageTranslations = resList
                    .filter(otherItem => otherItem.string_content === item.string_content && otherItem.target_language !== item.target_language);

                // Create a Set to filter out duplicates
                const seenTranslations = new Set();

                // Combine current and other language translations
                const translationResults = [
                    {
                        targetLanguage: item.target_language,
                        translationResult: item.translation_result
                    },
                    ...otherLanguageTranslations.map(otherItem => ({
                        targetLanguage: otherItem.target_language,
                        translationResult: otherItem.translation_result
                    }))
                ].filter(obj => {
                    const key = obj.targetLanguage + obj.translationResult;
                    if (seenTranslations.has(key)) {
                        return false;
                    } else {
                        seenTranslations.add(key);
                        return true;
                    }
                });

                return {
                    ...item,
                    translationResults
                };
            });
        },
        async oneClickTranslationHandel() {
            let query = {
                package_name: this.queryParams.packageName,
                version: this.$route.query.version,
            }
            const res = await oneClickTranslation(query)
            if (res.code == 0) {
                this.$message.success(res.message)
            } else {
                this.$message.error(res.message)
            }
        },
        getHandler() {
            return this.single ? this.QuerySingle() : this.getMore();
        },
        async handleQuerySingle() {
            this.queryParams.page = 1
            this.single = true
            const res = await getChildTaskListSingle(this.queryParams)
            res.data.forEach(element => {
                if (element.translationResults) {
                    element.translationResults = JSON.parse(element.translationResults)
                }
            });
            this.moreArr = res.data;
            this.total = res.total;
        },
        async QuerySingle() {
            this.single = true
            const res = await getChildTaskListSingle(this.queryParams)
            res.data.forEach(element => {
                if (element.translationResults) {
                    element.translationResults = JSON.parse(element.translationResults)
                }
            });
            this.moreArr = res.data;
            this.total = res.total;
        },
        async getLangListByPkHandel() {
            let query = {
                package_name: this.queryParams.packageName,
                version: this.$route.query.version,
            }
            const res = await getLangListByPk(query)
            if (res.data.length != 0) {
                this.languageList = res.data.map((item) => ({
                    id: item.target_language,
                    name: item.target_language,
                }));
            }

        },
        addValidationRules() {
            let rules = this.rules;
            if (this.form.translationResults && this.form.translationResults.length) {
                this.form.translationResults.forEach((item, index) => {
                    rules[`translationResults[${index}].translationResult`] = [
                        { required: true, message: `请输入${item.targetLanguage}翻译结果`, trigger: 'blur' }
                    ];
                });
            }

            this.$set(this, 'rules', rules);  // Ensure reactivity
        },
        async submitHandel() {
            let query = {
                packageName: this.queryParams.packageName,
                version: this.$route.query.version,
            }
            const res = await saveSubmit(query)
            if (res.success) {
                this.queryParams.page = 1
                this.queryParams.target_language = ''

                this.single = false
                this.$message.success(res.message);
                this.getMore();
            } else {

                this.$message.error(res.message);
            }
        },
        getSubstringAfter(str, delimiter) {
            const index = str.indexOf(delimiter);
            if (index !== -1) {
                return str.substring(index + delimiter.length);
            } else {
                return ""; // 如果没有找到分隔符，返回空字符串
            }
        },
        uploadHandel(e) {
            this.form.file = e.file;
        },
        remeveFile() {
            this.form.file = "";
        },
        timeChange() {
            this.queryParams.dateRange.start = this.value1[0];
            this.queryParams.dateRange.end = this.value1[1];
            this.handleQuery();
        },
        getKeyByValue(object, value) {
            return Object.keys(object).find((key) => object[key] === value);
        },
        async getMore() {
            this.loading = true;
            let { data, total } = await getChildTaskList(this.queryParams);
            data.forEach(element => {
                if (element.translationResults) {
                    element.translationResults = JSON.parse(element.translationResults)
                }
            });
            this.loading = false;
            this.moreArr = data;
            this.total = total;
        },

        handleQuery() {
            this.queryParams.page = 1;
            this.getMore();
        },
        translateHandel() {
            this.$refs["ruleForm"].validate(async (valid) => {
                if (!valid) return;
                this.translateLoading = true;
                let query = {
                    stringContent: this.form.stringContent,
                    multiLang: this.form.multiLang,
                    stringName: this.form.stringName,
                    translationMultiLangXml: this.form.translationMultiLangXml,

                };
                const res = await childTaskTranslateTextForMultiLang(query);
                if (res.success) {
                    this.translateLoading = false;
                    this.form.translationMultiLang = res.data.translationMultiLang;
                    this.form.stringContent = res.data.stringContent;
                    this.form.translationMultiLangXml = res.data.translationMultiLangXml;
                    this.form.translationResults = res.data.translationResults;
                } else {
                    this.translateLoading = false;
                    this.$message.error(res.message);
                }
            });
        },
        async affirm() {

            this.$refs["ruleForm"].validate(async (valid) => {
                if (!valid) return;
                if (!this.form.translationResults || this.form.translationResults.length == 0) return this.$message.error('未翻译')
                if (!this.form.translationMultiLangXml) {
                    this.form.translationMultiLangXml = JSON.stringify(this.form.translationResults)
                }

                this.confirmLoading = true
                this.form.packageName = this.queryParams.packageName
                this.form.version=this.$route.query.version
                const res = await saveChildBatch(this.form)
                if (res.success) {
                    this.confirmLoading = false;
                    this.$message.success(res.message);
                    if (this.single) {
                        this.QuerySingle()
                    } else {

                        this.getMore();
                    }
                    this.dialogVisible = false;
                } else {
                    this.confirmLoading = false;
                    this.$message.error(res.message);
                }
            });
        },
        openDialog() {
            this.form = {};
            this.dialogVisible = true;
        },
        handleEdit(i, row) {
            this.form = row;
            this.dialogVisible = true;
        },
        handleDelete(index, row) {
            this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "error",
            }).then(async () => {
                await deleteTemplateType({ id: row.id });
                this.getMore();
                this.$message({
                    message: "删除成功！",
                    type: "success",
                });
            });
        },
        resetQuery() {
            this.queryParams.page = 1;
            this.queryParams.target_language = '';
            this.single = false
            this.getMore();
        },
    },
};
</script>
<style lang="scss" scoped>
.boxs {
    padding: 20px;
}

::v-deep.el-input.is-disabled .el-input__inner {
    color: #333 !important;
}

::v-deep.el-textarea.is-disabled .el-textarea__inner {
    color: #333 !important;
}

::v-deep .el-upload {
    width: 100% !important;
}

::v-deep .el-upload-dragger {
    width: 100% !important;
}
</style>